<?php

namespace App\Services;

use App\Models\Order;
use App\Models\Payment;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class PaymentService
{
    /**
     * 创建支付记录
     */
    public function createPayment(Order $order, string $paymentMethod, array $data = []): Payment
    {
        return DB::transaction(function () use ($order, $paymentMethod, $data) {
            $payment = Payment::create([
                'order_id' => $order->id,
                'payment_method' => $paymentMethod,
                'amount' => $order->total_amount,
                'status' => 'pending',
                'transaction_id' => $data['transaction_id'] ?? null,
                'gateway_response' => $data['gateway_response'] ?? null,
                'expires_at' => now()->addMinutes(30), // 30分钟过期
            ]);

            Log::info('Payment created', [
                'payment_id' => $payment->id,
                'order_id' => $order->id,
                'order_number' => $order->order_number,
                'amount' => $payment->amount,
                'payment_method' => $paymentMethod,
            ]);

            return $payment;
        });
    }

    /**
     * 处理支付成功
     */
    public function handlePaymentSuccess(Payment $payment, array $gatewayData = []): void
    {
        DB::transaction(function () use ($payment, $gatewayData) {
            // 更新支付状态
            $payment->update([
                'status' => 'paid',
                'paid_at' => now(),
                'gateway_response' => $gatewayData,
            ]);

            // 更新订单状态
            $payment->order->markAsPaid();

            Log::info('Payment successful', [
                'payment_id' => $payment->id,
                'order_id' => $payment->order_id,
                'order_number' => $payment->order->order_number,
                'amount' => $payment->amount,
            ]);
        });
    }

    /**
     * 处理支付失败
     */
    public function handlePaymentFailure(Payment $payment, string $reason, array $gatewayData = []): void
    {
        DB::transaction(function () use ($payment, $reason, $gatewayData) {
            // 更新支付状态
            $payment->update([
                'status' => 'failed',
                'failed_at' => now(),
                'failure_reason' => $reason,
                'gateway_response' => $gatewayData,
            ]);

            // 更新订单状态
            $payment->order->update([
                'payment_status' => 'failed',
                'status' => 'cancelled',
            ]);

            Log::warning('Payment failed', [
                'payment_id' => $payment->id,
                'order_id' => $payment->order_id,
                'order_number' => $payment->order->order_number,
                'reason' => $reason,
            ]);
        });
    }

    /**
     * 处理支付取消
     */
    public function handlePaymentCancelled(Payment $payment, string $reason = null): void
    {
        DB::transaction(function () use ($payment, $reason) {
            // 更新支付状态
            $payment->update([
                'status' => 'cancelled',
                'cancelled_at' => now(),
                'cancellation_reason' => $reason,
            ]);

            // 更新订单状态
            $payment->order->update([
                'payment_status' => 'failed',
                'status' => 'cancelled',
            ]);

            Log::info('Payment cancelled', [
                'payment_id' => $payment->id,
                'order_id' => $payment->order_id,
                'order_number' => $payment->order->order_number,
                'reason' => $reason,
            ]);
        });
    }

    /**
     * 处理退款
     */
    public function processRefund(Payment $payment, float $amount, string $reason = null): Payment
    {
        return DB::transaction(function () use ($payment, $amount, $reason) {
            // 创建退款记录
            $refund = Payment::create([
                'order_id' => $payment->order_id,
                'payment_method' => $payment->payment_method,
                'amount' => -$amount, // 负数表示退款
                'status' => 'refunded',
                'refunded_at' => now(),
                'refund_reason' => $reason,
                'parent_payment_id' => $payment->id,
            ]);

            // 更新原支付记录
            $payment->update([
                'status' => 'refunded',
                'refunded_at' => now(),
            ]);

            // 更新订单状态
            $payment->order->update([
                'payment_status' => 'refunded',
            ]);

            Log::info('Refund processed', [
                'payment_id' => $payment->id,
                'refund_id' => $refund->id,
                'order_id' => $payment->order_id,
                'amount' => $amount,
                'reason' => $reason,
            ]);

            return $refund;
        });
    }

    /**
     * 获取支付记录
     */
    public function getPaymentByOrder(Order $order): ?Payment
    {
        return Payment::where('order_id', $order->id)
            ->where('status', '!=', 'cancelled')
            ->orderBy('created_at', 'desc')
            ->first();
    }

    /**
     * 获取订单的所有支付记录
     */
    public function getOrderPayments(Order $order): \Illuminate\Database\Eloquent\Collection
    {
        return Payment::where('order_id', $order->id)
            ->orderBy('created_at', 'desc')
            ->get();
    }

    /**
     * 检查支付是否过期
     */
    public function isPaymentExpired(Payment $payment): bool
    {
        return $payment->expires_at && $payment->expires_at->isPast();
    }

    /**
     * 取消过期的支付
     */
    public function cancelExpiredPayments(): int
    {
        $expiredPayments = Payment::where('status', 'pending')
            ->where('expires_at', '<', now())
            ->get();

        $count = 0;
        foreach ($expiredPayments as $payment) {
            $this->handlePaymentCancelled($payment, '支付超时自动取消');
            $count++;
        }

        if ($count > 0) {
            Log::info('Expired payments cancelled', ['count' => $count]);
        }

        return $count;
    }

    /**
     * 获取支付统计
     */
    public function getPaymentStats(array $filters = []): array
    {
        $query = Payment::query();

        // 时间范围筛选
        if (!empty($filters['start_date'])) {
            $query->where('created_at', '>=', $filters['start_date']);
        }
        if (!empty($filters['end_date'])) {
            $query->where('created_at', '<=', $filters['end_date']);
        }

        // 支付方式筛选
        if (!empty($filters['payment_method'])) {
            $query->where('payment_method', $filters['payment_method']);
        }

        $totalAmount = $query->where('status', 'paid')->sum('amount');
        $totalCount = $query->where('status', 'paid')->count();
        $successRate = $query->count() > 0 
            ? round($query->where('status', 'paid')->count() / $query->count() * 100, 2)
            : 0;

        return [
            'total_amount' => $totalAmount,
            'total_count' => $totalCount,
            'success_rate' => $successRate,
        ];
    }

    /**
     * 验证支付金额
     */
    public function validatePaymentAmount(Order $order, float $amount): bool
    {
        return abs($amount - $order->total_amount) < 0.01; // 允许1分钱的误差
    }

    /**
     * 生成支付URL（用于第三方支付）
     */
    public function generatePaymentUrl(Payment $payment): string
    {
        // 这里可以根据不同的支付方式生成不同的支付URL
        // 目前返回一个模拟的支付页面URL
        return route('payment.show', $payment->order->order_number);
    }
}
